import * as d3 from "d3";

type D3Selection = d3.Selection<any, any, any, any>;

class Icon {
  public viewBoxSize = 1024;

  /**
   * 图标默认尺寸
   */
  public defaultIconSize = 20;

  static SHAPEMAPPING = {
    "five-star":
      "M512 6.144L632.896 384H1024l-316.416 235.072 120.832 378.688L512 764.608l-316.416 233.728 120.832-379.328L0 384h391.104z",
    circle:
      "M116.4921875 512C116.4921875 293.56706665 294.01153401 116.4921875 512 116.4921875 730.43293335 116.4921875 907.5078125 294.01153401 907.5078125 512 907.5078125 730.43293335 729.98846599 907.5078125 512 907.5078125 293.56706665 907.5078125 116.4921875 729.98846599 116.4921875 512Z",
    triangle: "M512 148.25L92 875.75h840z",
    diamond:
      "M512 69.479l442.498 442.498-442.498 442.498-442.498-442.498 442.498-442.498z",
    rect: "M165.93066406 165.93066406h692.13867188v692.13867188H165.93066406z",
    fork: "M49.6 158.4l104-108.8 358.4 352 356.8-352 105.6 105.6-352 356.8 352 355.2-102.4 107.2L512 620.8 155.2 974.4l-105.6-105.6L406.4 512z",
    plus: "M577.088 0H448.96v448.512H0v128h448.96V1024h128.128V576.512H1024v-128H577.088z"
  };

  private uuid(): string {
    return "xxxxxxxxxxxxxxxx".replace(/x/g, () => {
      return Math.floor(Math.random() * 16)
        .toString(16)
        .toLowerCase();
    });
  }

  /**
   * 绘制图形
   * @param options
   * @param $def
   */
  public createIconMapping(
    config: TriangleChartSeryIconConfig,
    $def: D3Selection
  ): string {
    const id = "symbol_" + this.uuid();
    const symbol = $def
      .append("symbol")
      .attr("id", id)
      .attr("viewBox", `0 0 ${this.viewBoxSize} ${this.viewBoxSize}`);

    const rate = this.viewBoxSize / (config.size || this.defaultIconSize);

    symbol
      .append("path")
      .attr("d", Icon.SHAPEMAPPING[config.type || "circle"])
      .attr("fill", config.fill || "#000")
      .attr("stroke", config.stroke || "#000")
      .attr("stroke-width", (config.stroekWidth || 1) * rate);

    return id;
  }
}

export default new Icon();
